package lumis.service.report;

import java.util.Collection;

import lumis.doui.source.IDataProvider;
import lumis.doui.source.ISourceData;
import lumis.doui.source.TabularData;
import lumis.doui.source.TabularSource;
import lumis.doui.source.field.ISourceField;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;

import lumis.util.ITransaction;
import lumis.portal.report.Report;
import lumis.portal.report.ReportParameter;

/**
 * Provides the parameters and their appropriate values for a given report.
 * <p>
 * The source must have a parameter value <em>id</em> with the identifier of
 * the report.
 *
 * @version $Revision: 9285 $ $Date: 2008-05-14 17:36:34 -0300 (Wed, 14 May 2008) $
 * @since 4.1.0
 */
public class ReportParametersDataProvider implements IDataProvider<TabularSource<?>>
{
	public void loadData(SessionConfig sessionConfig, TabularSource<?> source, ITransaction transaction) throws PortalException
	{
		TabularData tabularData = source.getData();
		String reportId = (String)source.getParameterValue("id");
		
		if (reportId == null)
			throw new IllegalStateException("'id' parameter not set in source '" + source.getId() + "'");
		
		Report report = ManagerFactory.getEntityManager().find(Report.class, reportId);
		Collection<ReportParameter> reportParameters = report.getParameters();

		ISourceData sourceData = tabularData.addRow();
		for (ReportParameter parameter: reportParameters)
		{
			Object value = null;
			ISourceField field = source.getField(parameter.getName());
			if(field != null)
				value = field.getConverter().convert(field.getValueClass(), parameter.getValue(), field.getDataType().getDefinitionLocale(), field.getDataType().getDefinitionPattern());
			else
				value = parameter.getValue();

			sourceData.put(parameter.getName(), value);
		}
	}
}
